package com.wechat.mp;

import com.google.gson.Gson;
import com.util.AccessTokenUtil;
import com.util.JSTicketUtil;
import com.wechat.mina.Constants;
import com.util.WeiXinUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 微信获取AccessToken并本地保存
 */
public class WxAccessToken {
    private static final long MAX_TIME = 7000;// 微信允许最长Access_token有效时间为7200秒,这里设置为7000秒

    public static AccessTokenUtil access_token_obj = null;

    public static JSTicketUtil js_ticket_obj = null;


    /**
     * 获取Access_token 保存并且只保存2小时Access_token。如果超过两个小时重新获取；如果没有超过两个小时，直接获取
     * 思路:将获取到的Access_token和当前时间存储到file里，
     * 取出时判断当前时间和存储里面的记录的时间的时间差，如果大于MAX_TIME,重新获取，并且将获取到的存储到file替换原来的内容
     * 如果小于MAX_TIME，直接获取。
     */
    public static String getSavedAccessToken() throws IOException {
        Gson gson = new Gson();
        String mAccess_token = null;// 需要获取的Access_token;
        System.out.println(System.getProperty("user.dir"));
        File file = new File("access_token.txt");// Access_token保存的位置
        // 如果文件不存在，创建
        if (!file.exists())
            file.createNewFile();
        // 如果文件大小等于0，说明第一次使用，存入Access_token

        if (file.length() == 0) {
            access_token_obj = WeiXinUtil.getToken();
            String token = access_token_obj.getToken();
            mAccess_token = token;
            FileOutputStream fos = new FileOutputStream("access_token.txt", false);// 不允许追加
            AccessTokenUtil at = new AccessTokenUtil();
            at.setToken(token);
            at.setExpiresIn(Integer.valueOf(System.currentTimeMillis() / 1000 + ""));
            String json = gson.toJson(at);
            fos.write(json.getBytes());
            fos.close();
        } else {
            // 读取文件内容
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[2048];
            int len = fis.read(b);
            String mJsonAccess_token = new String(b, 0, len);// 读取到的文件内容

            AccessTokenUtil access_token = gson.fromJson(mJsonAccess_token, new AccessTokenUtil().getClass());
            if (access_token.getExpiresIn() != null) {
                long lastSaveTime = Long.parseLong(access_token.getExpiresIn() + "");
                long nowTime = System.currentTimeMillis() / 1000;
                long remianTime = nowTime - lastSaveTime;
                if (remianTime < MAX_TIME) {
                    AccessTokenUtil access = gson.fromJson(mJsonAccess_token, new AccessTokenUtil().getClass());
                    mAccess_token = access.getToken();
                } else {
                    access_token_obj = WeiXinUtil.getToken();
                    FileOutputStream fos = new FileOutputStream(file, false);// 不允许追加
                    AccessTokenUtil newToken = new AccessTokenUtil();
                    mAccess_token = access_token_obj.getToken();
                    newToken.setToken(access_token_obj.getToken());
                    newToken.setExpiresIn(Integer.valueOf(System.currentTimeMillis() / 1000 + ""));
                    String json = gson.toJson(newToken);
                    fos.write((json).getBytes());
                    fos.close();
                }
            }
        }
        return mAccess_token;
    }


    public static String getSavedJsapiTicket(String access_token) throws IOException {
        Gson gson = new Gson();
        String mJs_ticket = null;// 需要获取的Access_token;
        System.out.println(System.getProperty("user.dir"));
        File file = new File("jsapi_ticket.txt");// jsapi_ticket保存的位置
        // 如果文件不存在，创建
        if (!file.exists())
            file.createNewFile();
        // 如果文件大小等于0，说明第一次使用，存入jsapi_ticket

        if (file.length() == 0) {
            js_ticket_obj = WeiXinUtil.getJsTicket(access_token);
            String ticket = js_ticket_obj.getTicket();
            FileOutputStream fos = new FileOutputStream("jsapi_ticket.txt", false);// 不允许追加
            JSTicketUtil at = new JSTicketUtil();
            at.setTicket(ticket);
            at.setExpiresIn(Integer.valueOf(System.currentTimeMillis() / 1000 + ""));
            String json = gson.toJson(at);
            fos.write(json.getBytes());
            fos.close();
        } else {
            // 读取文件内容
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[2048];
            int len = fis.read(b);
            String mJsonJs_ticket = new String(b, 0, len);// 读取到的文件内容

            JSTicketUtil js_ticket = gson.fromJson(mJsonJs_ticket, new JSTicketUtil().getClass());
            if (js_ticket.getExpiresIn() != null) {
                long lastSaveTime = Long.parseLong(js_ticket.getExpiresIn() + "");
                long nowTime = System.currentTimeMillis() / 1000;
                long remianTime = nowTime - lastSaveTime;
                if (remianTime < MAX_TIME) {
                    JSTicketUtil jsTicket = gson.fromJson(mJsonJs_ticket, new JSTicketUtil().getClass());
                    mJs_ticket = jsTicket.getTicket();
                } else {
                    js_ticket_obj = WeiXinUtil.getJsTicket(access_token);
                    FileOutputStream fos = new FileOutputStream(file, false);// 不允许追加
                    JSTicketUtil newJSTicket = new JSTicketUtil();
                    newJSTicket.setTicket(js_ticket_obj.getTicket());
                    newJSTicket.setExpiresIn(Integer.valueOf(System.currentTimeMillis() / 1000 + ""));
                    mJs_ticket = js_ticket_obj.getTicket();
                    String json = gson.toJson(newJSTicket);
                    fos.write((json).getBytes());
                    fos.close();
                }
            }
        }
        return mJs_ticket;
    }

    public static String getSavedAgentJsapiTicket(String access_token) throws IOException {
        Gson gson = new Gson();
        String mJs_ticket = null;// 需要获取的Access_token;
        System.out.println(System.getProperty("user.dir"));
        File file = new File("agent_jsapi_ticket.txt");// jsapi_ticket保存的位置
        // 如果文件不存在，创建
        if (!file.exists())
            file.createNewFile();
        // 如果文件大小等于0，说明第一次使用，存入jsapi_ticket

        if (file.length() == 0) {
            js_ticket_obj = WeiXinUtil.getAgentJsTicket(access_token);
            String ticket = js_ticket_obj.getTicket();
            FileOutputStream fos = new FileOutputStream("agent_jsapi_ticket.txt", false);// 不允许追加
            JSTicketUtil at = new JSTicketUtil();
            at.setTicket(ticket);
            at.setExpiresIn(Integer.valueOf(System.currentTimeMillis() / 1000 + ""));
            String json = gson.toJson(at);
            fos.write(json.getBytes());
            fos.close();
        } else {
            // 读取文件内容
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[2048];
            int len = fis.read(b);
            String mJsonJs_ticket = new String(b, 0, len);// 读取到的文件内容

            JSTicketUtil js_ticket = gson.fromJson(mJsonJs_ticket, new JSTicketUtil().getClass());
            if (js_ticket.getExpiresIn() != null) {
                long lastSaveTime = Long.parseLong(js_ticket.getExpiresIn() + "");
                long nowTime = System.currentTimeMillis() / 1000;
                long remianTime = nowTime - lastSaveTime;
                if (remianTime < MAX_TIME) {
                    JSTicketUtil jsTicket = gson.fromJson(mJsonJs_ticket, new JSTicketUtil().getClass());
                    mJs_ticket = jsTicket.getTicket();
                } else {
                    js_ticket_obj = WeiXinUtil.getAgentJsTicket(access_token);
                    FileOutputStream fos = new FileOutputStream(file, false);// 不允许追加
                    JSTicketUtil newJSTicket = new JSTicketUtil();
                    newJSTicket.setTicket(js_ticket_obj.getTicket());
                    newJSTicket.setExpiresIn(Integer.valueOf(System.currentTimeMillis() / 1000 + ""));
                    mJs_ticket = js_ticket_obj.getTicket();
                    String json = gson.toJson(newJSTicket);
                    fos.write((json).getBytes());
                    fos.close();
                }
            }
        }
        return mJs_ticket;
    }

    public static void main(String args[]) throws IOException {
        WxAccessToken.getSavedAccessToken();
    }
}
